import { PlusOutlined, ProfileOutlined, PartitionOutlined, DeleteOutlined, UnorderedListOutlined, SettingOutlined, ImportOutlined, ExportOutlined } from '@ant-design/icons';
import { Button, Drawer, message, Modal, Row, Col, Form, Space, Tag, InputNumber } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable, { EditableProTable } from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import { ModalForm, ProFormSelect, ProFormText, ProFormMoney, ProFormTextArea, ProFormSwitch, ProFormDatePicker } from '@ant-design/pro-form';
import {
  useAccess,
} from 'umi';

import { lossOilStock, transOilStock, getInStockList, getOilList, createOil, getOilInfo, updateOil, getSupplierByPro, reduceOilStock, addOilStock, getOilStockLog } from './service'
import { getSupplierList } from '../supplier/service'
import { getProviderList } from '../provider/service'

import type { transOilStockParams, supplierByProItem, oilListParams, createOilParams, oilInfoParams, updateOilParams, reduceOilStockParams, addOilStockParams } from './data';

const TableList: React.FC = () => {

  const [editForm] = Form.useForm()

  const access = useAccess();

  const [currentId, setCurrentId] = useState<number>();
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [updateModalVisible, setUpdateModalVisible] = useState(false);
  const [exportModalVisible, setExportModalVisible] = useState(false);
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [logModalVisible, setLogModalVisible] = useState(false);
  const [stockModalVisible, setStockModalVisible] = useState(false);
  const [selectedSupplierRowsState, setSelectedSupplierRows] = useState<supplierByProItem[]>([]);
  const [transModalVisible, setTransModalVisible] = useState(false);
  const [orderModalVisible, setOrderModalVisible] = useState(false);
  const [lossStockModalVisible, setLossStockModalVisible] = useState(false);

  const [importProviderId, setImportProviderId] = useState<string>();
  const [supplierData, setSupplierData] = useState({});

  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef<ActionType>();
  const supplierListRef = useRef<ActionType>();

  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() => []);
  const [currentRow, setCurrentRow] = useState<oilListParams>();

  const [dataSource, setDataSource] = useState<addOilStockParams[]>(() => []);

  useEffect(() => {
    const fetchData = async (parmas) => {
      parmas = {
        provider_id: importProviderId,
        ...parmas,
      }
      const res = await getSupplierList({ ...parmas })
      var obj = {};
      res.data.list.map((item) => {
        const id = item.id
        obj[id] = {
          text: `${item.name}`
        }
      })
      setSupplierData(obj)
    }
    !!importProviderId && fetchData([])
  }, [importProviderId])

  useEffect(() => {
    const reset = () => {
      editForm.resetFields()
      setImportProviderId('')
      setEditableRowKeys([])
      setDataSource([])
      setCurrentId(undefined)
      setSupplierData([])
    }
    !importModalVisible && reset()
  }, [importModalVisible])

  const oilListColumns: ProColumns<oilListParams>[] = [
    // {
    //   title: '货品ID',
    //   hideInSearch: true,
    //   dataIndex: 'id',
    // },
    {
      title: '货品名称',
      dataIndex: 'oil_name',
      render: (dom, rowData) => {
        return access.getProviderInfo && rowData.is_checked === 1 ? <a onClick={() => {
          setCurrentRow(rowData);
          setShowDetail(true);
        }}
        >{dom}</a>
          : `${dom}`
      },
    },
    {
      title: '货品类型',
      dataIndex: 'oil_type',
    },
    {
      title: '状态',
      width: 100,
      dataIndex: 'is_checked',
      valueType: 'select',
      filters: true,
      onFilter: true,
      hideInSearch: true,
      valueEnum: {
        0: { text: '未启用', status: 'Default', },
        1: { text: '启用中', status: 'Success', },
      },
    },
    {
      title: '库存余量',
      align: 'right',
      dataIndex: 'stock',
      sorter: (a, b) => a.stock - b.stock,
      hideInSearch: true,
      render: (val, rowData) => {
        return (
          !!val && `${val} ${rowData.unit}`
        )
      },
    },
    {
      title: '仓库列表',
      valueType: 'option',
      render: (_, rowData) => {
        if (rowData.is_checked === 1) {
          return (
            <a onClick={() => {
              setCurrentRow(rowData)
              setStockModalVisible(true)
            }} >库存管理</a>)
        } else {
          return ''
        }
      }
    },
    {
      title: '操作',
      valueType: 'option',
      width: 500,
      render: (_, rowData) => [
        !!access.addOilStock && <Button
          key="reduceAddOilStock"
          type="primary"
          ghost
          disabled={rowData.is_checked === 0}
          shape="round"
          icon={<ImportOutlined />}
          onClick={() => {
            setCurrentRow(rowData);
            setImportModalVisible(true)
          }}
        >入库</Button>,
        !!access.updateOil && <Button
          key="updateOil"
          type="primary"
          icon={<SettingOutlined />}
          onClick={() => {
            setCurrentRow(rowData)
            setUpdateModalVisible(true)
          }}
        >货品管理</Button>,
        !!access.getOilStockLog &&
        <Button
          key="getLog"
          icon={<ProfileOutlined />}
          onClick={() => {
            setCurrentId(rowData.id);
            setLogModalVisible(true)
          }}
        >日志</Button>
      ],
    },
  ]

  return (
    <PageContainer>
      <ProTable<oilListParams>
        headerTitle="货品列表"
        loading={false}
        actionRef={actionRef}
        rowKey="id"
        bordered={true}
        columns={oilListColumns}
        pagination={{
          pageSize: 10,
          current: 1
        }}
        toolBarRender={() => [
          !!access.createOil &&
          <Button
            key="add"
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >新增货品</Button>,
        ]}
        search={{
          resetText: '重置查询',
          searchText: '查询货品',
        }}
        request={async (params) => {
          const dataParams = {
            page: params.current,
            limit: params.pageSize,
            oil_name: params.oil_name,
            oil_type: params.oil_type,
          }
          const res = await getOilList({ ...dataParams });
          return {
            data: res.data.list,
            success: res.code === 200,
            total: res.data.total,
          };
        }}
      />


      {/* 货品出库 */}
      {
        !!exportModalVisible &&
        <ModalForm<reduceOilStockParams>
          width={600}
          title={'货品出库'}
          visible={exportModalVisible}
          onVisibleChange={setExportModalVisible}
          onFinish={
            async (value) => {
              const res = await reduceOilStock({ ...value });
              if (res.code === 200) {
                message.success('出库成功')
                if (actionRef.current) {
                  actionRef.current.reload();
                }
                if (supplierListRef.current) {
                  supplierListRef.current.reload();
                }
              } else {
                message.error(res.msg)
              }
              setExportModalVisible(false)
            }
          }
        >
          <ProFormText
            name="oil_id"
            hidden
            initialValue={currentRow?.id}
          />
          <ProFormText
            name="oil_depot_id"
            hidden
            initialValue={currentId}
          />
          <Row gutter={12}>
            <Col span="12">
              <ProFormText
                name="stock_change"
                label="货品出库量"
                placeholder="请输入货品出库量"
                rules={[{ required: true, message: '货品出库量不能为空!' }]}
              />
            </Col>
            <Col span="12" >
              <ProFormMoney
                name="price"
                label="货品出库价格"
                tooltip="不填写价格即为当前货品的价格"
                placeholder="请输入货品出库价格"
                fieldProps={
                  {
                    stringMode: true,
                    precision:3,

                  }
                }
              />

            </Col>
            <Col span="12">
              <ProFormDatePicker
                name="exp_date"
                width="lg"
                label="出库时间"
                placeholder="请选择出库时间"
                rules={[{ required: true, message: '出库时间不能为空!' }]}
              />
            </Col>
            <Col span="12">
              <ProFormText
                name="company_name"
                label="出库公司名称"
                placeholder="请输入出库公司名称"
                rules={[{ required: true, message: '出库公司名称不能为空!' }]}
              />
            </Col>
            <Col span="12">
              <ProFormText
                name="company_man"
                label="出库公司联系人"
                placeholder="请输入出库公司联系人"
                rules={[{ required: true, message: '出库公司联系人不能为空!' }]}
              />
            </Col>
            <Col span="12">
              <ProFormText
                name="company_phone"
                label="出库公司联系方式"
                placeholder="请输入出库公司联系方式"
                rules={[{ required: true, message: '出库公司联系方式不能为空!' }]}
              />
            </Col>

          </Row>
          <ProFormTextArea
            name="desc"
            label="出库备注"
          />
        </ModalForm>

      }


      {/* 货品报损 */}
      {
        !!lossStockModalVisible && (
          <ModalForm<transOilStockParams>
            width={600}
            initialValues={
              {
                oil_id: currentRow?.id,
                supplier_id: currentId,
              }
            }
            title={'库存报损'}
            visible={lossStockModalVisible}
            onVisibleChange={setLossStockModalVisible}
            onFinish={
              async (value) => {
                const res = await lossOilStock({ ...value });
                if (res.code === 200) {
                  message.success('库存报损成功')
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                  if (supplierListRef.current) {
                    supplierListRef.current.reload();
                  }
                } else {
                  message.error(res.msg)
                }
                setLossStockModalVisible(false)
              }
            }
          >
            <ProFormText
              name="oil_id"
              hidden
            />
            <ProFormText
              name="supplier_id"
              hidden
            />
            <Row gutter={12}>
              <Col span="12">
                <ProFormText
                  name="stock_change"
                  label="报损数量"
                  placeholder="请输入报损数量"
                  rules={[{ required: true, message: '货报损数量不能为空!' }]}
                />
              </Col>
              <Col span="12">
                <ProFormSelect
                  name="pc_no"
                  label="入库批次号"
                  fieldProps={{
                    showArrow: true,
                  }}
                  placeholder="请选择入库批次号"
                  rules={[{ required: true, message: '货品入库批次号不能为空!' }]}
                  request={async () => {
                    const dataParams = {
                      oildepot_id: currentId,
                      product_id: currentRow?.id,
                    }
                    const res = await getInStockList({ ...dataParams });

                    const data = res.data.list
                    const optionsData = new Array;
                    data.forEach(item => {
                      item.id !== currentId &&
                        optionsData.push({
                          label: item.pc_no,
                          value: item.pc_no,
                        });
                    });
                    return optionsData;
                  }}
                />

              </Col>

            </Row>
            <ProFormTextArea
              name="desc"
              label="报损备注"
            />
          </ModalForm>
        )
      }



      {/* 货品转移出库 */}
      {
        !!transModalVisible && (
          <ModalForm<transOilStockParams>
            width={600}
            initialValues={
              {
                oil_id: currentRow?.id,
                out_supplier_id: currentId,
              }
            }
            title={'货品转移出库'}
            visible={transModalVisible}
            onVisibleChange={setTransModalVisible}
            onFinish={
              async (value) => {
                const res = await transOilStock({ ...value });
                if (res.code === 200) {
                  message.success('转移出库成功')
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                  if (supplierListRef.current) {
                    supplierListRef.current.reload();
                  }
                } else {
                  message.error(res.msg)
                }
                setTransModalVisible(false)
              }
            }
          >
            <ProFormText
              name="oil_id"
              hidden
            />
            <ProFormText
              name="out_supplier_id"
              hidden
            />
            <Row gutter={12}>
              <Col span="12">
                <ProFormSelect
                  name="in_supplier_id"
                  label="货品转入仓库"
                  fieldProps={{
                    // mode: 'multiple',
                    showArrow: true,
                  }}
                  placeholder="请选择货品转入仓库"
                  rules={[{ required: true, message: '请选择至少一项货品转入仓库!' }]}
                  request={async (params) => {
                    const res = await getSupplierList({ ...params });
                    const data = res.data.list
                    const optionsData = new Array;
                    data.forEach(item => {
                      item.id !== currentId &&
                        optionsData.push({
                          label: item.name,
                          value: item.id,
                        });
                    });
                    return optionsData;
                  }}
                />
              </Col>
              <Col span="12">
                <ProFormText
                  name="stock_change"
                  label="货品转移出库量"
                  placeholder="请输入货品转移出库量"
                  rules={[{ required: true, message: '货品转移出库量不能为空!' }]}
                />
              </Col>
              <Col span="12">
                <ProFormSelect
                  name="pc_no"
                  label="入库批次号"
                  fieldProps={{
                    showArrow: true,
                  }}
                  placeholder="请选择入库批次号"
                  rules={[{ required: true, message: '货品入库批次号不能为空!' }]}
                  request={async () => {
                    const dataParams = {
                      oildepot_id: currentId,
                      product_id: currentRow?.id,
                      is_has: 1,
                    }
                    const res = await getInStockList({ ...dataParams });

                    const data = res.data.list
                    const optionsData = new Array;
                    data.forEach(item => {
                      // item.id !== currentId &&
                      optionsData.push({
                        label: item.pc_no,
                        value: item.pc_no,
                      });
                    });
                    return optionsData;
                  }}
                />

              </Col>
              <Col span="12">
                <ProFormDatePicker
                  name="trans_date"
                  width="lg"
                  label="转库时间"
                  placeholder="请选择转库时间"
                  rules={[{ required: true, message: '转库时间不能为空!' }]}
                />
              </Col>



            </Row>
            <ProFormTextArea
              name="desc"
              label="转移出库备注"
            />
          </ModalForm>
        )
      }

      {/* 货品入库 */}
      {
        !!importModalVisible && (
          <Modal
            destroyOnClose
            width={1200}
            maskClosable={false}
            title={`货品入库 (${currentRow?.oil_name})`}
            visible={importModalVisible}
            onCancel={() => {
              setImportModalVisible(false)
            }}
            footer={null}
          >
            <EditableProTable
              rowKey="id"
              toolbar={
                {
                  prefixCls: 'left-toolbar',
                  style: {
                    marginBottom: '15px'
                  }
                }
              }
              onChange={setDataSource}
              toolBarRender={() => [
                <ProFormSelect
                  noStyle
                  showSearch
                  label="供应商"
                  disabled={!!importProviderId}
                  placeholder="请选择供应商"
                  request={async (params) => {
                    const res = await getProviderList({ ...params });
                    const data = res.data.list
                    return data.map((item) => {
                      return {
                        label: item.name,
                        value: item.id,
                      };
                    });
                  }}
                  fieldProps={{
                    onChange: (val) => {
                      editForm.resetFields()
                      setImportProviderId(val.value)
                    },
                    labelInValue: true
                  }}
                />,
                <Button
                  key="importBtn"
                  type="primary"
                  onClick={async () => {
                    const data = {
                      provider_id: importProviderId,
                      oil_id: currentRow?.id,
                      list: {
                        ...dataSource
                      }
                    }
                    if (dataSource.length <= 0) {
                      message.error('请先保存至少一行数据！')
                    } else {
                      const res = await addOilStock({ ...data });
                      if (res.code === 200) {
                        message.success('入库成功')
                        if (actionRef.current) {
                          actionRef.current.reload();
                        }
                        setImportModalVisible(false)
                      } else {
                        message.error(res.msg)
                      }
                    }

                  }}
                >确认入库</Button>
              ]}
              recordCreatorProps={{
                // position: 'bottom',
                // newRecordType: 'dataSource',
                record: () => ({
                  id: Date.now(),
                }),
              }}
              editable={{
                editableKeys,
                form: editForm,
                onChange: (e, editableRows) => {
                  setEditableRowKeys(e)
                },
                onSave: async (rowKey, data, row) => {
                },
              }}
              columns={[
                {
                  title: '仓库',
                  dataIndex: 'oil_depot_id',
                  valueType: 'select',
                  valueEnum: supplierData,
                  fieldProps: () => {
                    return {
                      style: { 'width': '100%' },
                    };
                  },
                  formItemProps: () => {
                    return {
                      rules: [
                        { required: true, message: !importProviderId ? '请先选择供应商！' : '仓库不能为空！' },
                      ]
                    };
                  },
                },
                {
                  title: '库存变动的量',
                  dataIndex: 'stock_change',
                  fieldProps: () => {
                    return {
                      style: { 'width': '100%' },
                    };
                  },
                  formItemProps: () => {
                    return {
                      rules: [{ required: true, message: '库存变动的量不能为空！' }]
                    };
                  },
                },
                {
                  title: '货品入库时间',
                  dataIndex: 'stock_date',
                  valueType: 'date',
                  fieldProps: () => {
                    return {
                      style: { 'width': '100%' },
                    };
                  },
                },
                {
                  title: '货品入库价格',
                  dataIndex: 'stock_price',
                  // valueType: 'money',
                  fieldProps: () => {
                    return {
                      style: { 'width': '100%' },
                      stringMode: true
                    };
                  },
                  // formItemProps: (form, { rowIndex }) => {
                  //   return {
                  //     rules: [{ required: true, message: '货品入库价格不能为空！' }]
                  //   };
                  // },
                },
                {
                  title: '生产日期',
                  dataIndex: 'product_date',
                  valueType: 'date',
                  fieldProps: () => {
                    return {
                      style: { 'width': '100%' },
                    };
                  },
                  // formItemProps: (form, { rowIndex }) => {
                  //   return {
                  //     rules: [{ required: true, message: '请选择生产日期！' }]
                  //   };
                  // },
                },
                {
                  title: '保质期限（天）',
                  dataIndex: 'baozhiqi',
                  fieldProps: () => {
                    return {
                      style: { 'width': '100%' },
                    };
                  },
                  // formItemProps: (form, { rowIndex }) => {
                  //   return {
                  //     rules: [{ required: true, message: '请选择保质期限！' }]
                  //   };
                  // },
                },
                {
                  title: '操作',
                  valueType: 'option',
                  width: 200,
                  render: (text, record, _, action) => [
                    <a
                      key="editable"
                      onClick={() => {
                        setEditableRowKeys([record.id])
                      }}
                    >
                      编辑
                    </a>,
                    <EditableProTable.RecordCreator
                      key="copy"
                      record={{
                        ...record,
                        id: Date.now()
                      }}
                    >
                      <a onClick={() => { }}>复制此行到末尾</a>
                    </EditableProTable.RecordCreator>,
                  ],
                },
              ]}>
            </EditableProTable>
          </Modal>
        )
      }

      {/* 新增货品 */}
      {
        !!createModalVisible && (
          <ModalForm<createOilParams>
            width={600}
            title={'新增货品'}
            visible={createModalVisible}
            onVisibleChange={setCreateModalVisible}
            initialValues={{
              'is_checked': 1,
            }}
            onFinish={
              async (value) => {
                const res = await createOil({ ...value });
                if (res.code === 200) {
                  message.success('添加成功')
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                } else {
                  message.error('添加失败')
                }
                setCreateModalVisible(false)
              }
            }
          >
            <Row gutter={12}>
              <Col span="8">
                <ProFormText
                  name="oil_name"
                  label="货品名称"
                  placeholder="请输入货品名称"
                  rules={[{ required: true, message: '货品名称不能为空!' }]}
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="oil_type"
                  label="货品类型"
                  placeholder="请输入货品类型"
                  rules={[{ required: true, message: '货品名称不能为空!' }]}
                />
              </Col>
              <Col span="4" push="1">
                <ProFormSwitch label="是否启用" name="is_checked" checkedChildren="是" unCheckedChildren="否" />
              </Col>
            </Row>
            <Row gutter={12}>

              <Col span="8">
                <ProFormText
                  name="unit"
                  placeholder="请输入货品计价单位"
                  tooltip="例如（吨）"
                  label="计价单位"
                  rules={[{ required: true, message: '请设置货品计价单位!' }]}
                />
              </Col>
              {/* <Col span="8">
                <ProFormSelect
                  name="supplier_id"
                  label="关联仓库"
                  fieldProps={{
                    mode: 'multiple',
                    showArrow: true,
                  }}
                  placeholder="请选择关联仓库"
                  rules={[{ required: true, message: '请选择至少一项关联仓库!' }]}
                  request={async (params) => {
                    const res = await getSupplierList({ ...params });
                    const data = res.data.list

                    const optionsData = new Array;

                    data.forEach(item => {
                      optionsData.push({
                        label: item.name,
                        value: item.id,
                      });
                    });
                    return optionsData;
                  }}
                />
              </Col> */}
              <Col span="8">
                <ProFormMoney
                  name="price"
                  placeholder="请输入货品预期零售价"
                  label="预期零售价"
                  fieldProps={
                    {
                      stringMode: true,
                      precision:3

                    }
                  }
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="brand"
                  label="品牌"
                  placeholder="请输入货品品牌"
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="specs"
                  label="规格"
                  placeholder="请输入货品规格"
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="product_area"
                  label="产地"
                  placeholder="请输入货品产地"
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="bar_code"
                  label="条形码"
                  placeholder="请输入货品条形码"
                />
              </Col>
            </Row>
            <ProFormTextArea
              name="remarks"
              label="货品备注"
            />
          </ModalForm>
        )
      }

      {/* 库存日志 */}
      {
        !!logModalVisible && (
          <Modal
            title="库存日志"
            width={1200}
            visible={logModalVisible}
            onCancel={() => {
              setCurrentId(undefined)
              setLogModalVisible(false)
            }}
            footer={null}
          >
            <ProTable
              headerTitle="库存变化日志"
              rowKey="id"
              search={{ labelWidth: 'auto' }}
              request={async (params) => {
                const dataParams = {
                  oil_id: currentId,
                  page: params.current,
                  limit: params.pageSize,
                  bdate: params.bdate,
                  edate: params.edate
                }
                const res = await getOilStockLog({ ...dataParams });
                return {
                  data: res.data.list,
                  success: res.code === 200,
                  total: res.data.total,
                };
              }}
              columns={[
                {
                  title: '操作时间',
                  width: 200,
                  hideInSearch: true,
                  dataIndex: 'created_at',
                },
                {
                  title: '变动时间',
                  dataIndex: 'searchDate',
                  hideInTable: true,
                  valueType: 'dateTimeRange',
                  search: {
                    transform: (value: any) => ({ bdate: value[0], edate: value[1] }),
                  },
                },
                {
                  title: '变动类型',
                  width: 120,
                  align: 'center',
                  dataIndex: 'change_type',
                  valueType: 'select',
                  filters: true,
                  onFilter: true,
                  hideInSearch: true,
                  valueEnum: {
                    1: { text: '入库' },
                    2: { text: '出库' },
                    6: { text: '移库(出)' },
                    7: { text: '移库(入)' },
                    8: { text: '报损' },
                    9: { text: '移库(补）' },
                  },
                },
                {
                  title: '变动量',
                  dataIndex: 'num',
                  hideInSearch: true,
                  render: (value, rowData) =>
                    rowData.type === 1 ? <span style={{ color: '#7cb305', fontWeight: 500, fontSize: '15px' }}>+ {value}</span> :
                      rowData.type === 2 ? <span style={{ color: '#f5222d', fontWeight: 500, fontSize: '15px' }}>- {value}</span> : ''
                },
                {
                  title: '操作人员',
                  hideInSearch: true,
                  dataIndex: 'username',
                },
                {
                  title: '操作备注',
                  hideInSearch: true,
                  dataIndex: 'desc',
                },
              ]
              }
              pagination={{
                pageSize: 10,
                current: 1,
              }}>
            </ProTable>
          </Modal>
        )
      }

      {/* 更新货品 */}
      {
        !!updateModalVisible && (
          <ModalForm<updateOilParams>
            width={600}
            title={'修改货品信息'}
            initialValues={
              {
                oil_id: currentRow?.id
              }
            }
            visible={updateModalVisible}
            onVisibleChange={setUpdateModalVisible}
            request={async () => {
              const params = {
                oil_id: currentRow?.id,
              }
              const res = await getOilInfo({ ...params });
              const data = res.data.info
              data.old_price = res.data.info.price

              return data;
            }}
            onFinish={
              async (value) => {
                const res = await updateOil({ ...value });
                if (res.code === 200) {
                  message.success('更新成功')
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                } else {
                  message.error('更新失败')
                }
                setUpdateModalVisible(false)
              }
            }
          >
            <ProFormText
              name="oil_id"
              hidden
            />
            <ProFormText
              name="old_price"
              hidden
            />
            <Row gutter={12}>
              <Col span="8">
                <ProFormText
                  name="oil_name"
                  label="货品名称"
                  placeholder="请输入货品名称"
                  rules={[{ required: true, message: '货品名称不能为空!' }]}
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="oil_type"
                  label="货品类型"
                  placeholder="请输入货品类型"
                  rules={[{ required: true, message: '货品名称不能为空!' }]}
                />
              </Col>
              <Col span="8" push="1">
                <ProFormSwitch label="是否启用" name="is_checked" checkedChildren="是" unCheckedChildren="否" />
              </Col>
            </Row>
            <Row gutter={12}>

              <Col span="8">
                <ProFormText
                  name="unit"
                  placeholder="请输入货品计价单位"
                  tooltip="例如（吨）"
                  label="计价单位"
                  rules={[{ required: true, message: '请设置货品计价单位!' }]}
                />
              </Col>
              {/* <Col span="8">
                <ProFormSelect
                  name="supplier_id"
                  label="关联仓库"
                  // fieldProps={{
                  //   mode: 'multiple',
                  // }}
                  placeholder="请选择关联仓库"
                  rules={[{ required: true, message: '请选择至少一项关联仓库!' }]}
                  request={async (params) => {
                    const res = await getSupplierList({ ...params });
                    const data = res.data.list

                    const optionsData = new Array;

                    data.forEach(item => {
                      optionsData.push({
                        label: item.name,
                        value: item.id,
                      });
                    });
                    return optionsData;
                  }}
                />
              </Col> */}
              <Col span="8">
                <ProFormMoney
                  name="price"
                  placeholder="请输入货品预期零售价"
                  label="预期零售价"
                  fieldProps={
                    {
                      stringMode: true,
                      precision:3
                    }
                  }
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="brand"
                  label="品牌"
                  placeholder="请输入货品品牌"
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="specs"
                  label="规格"
                  placeholder="请输入货品规格"
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="product_area"
                  label="产地"
                  placeholder="请输入货品产地"
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="bar_code"
                  label="条形码"
                  placeholder="请输入货品条形码"
                />
              </Col>
            </Row>
            <ProFormTextArea
              name="remarks"
              label="备注"
              placeholder=""
            />
          </ModalForm>
        )
      }
      {/* 库存列表 */}
      {
        !!stockModalVisible && (
          <Modal
            visible={stockModalVisible}
            title='库存列表'
            width={1200}
            footer={null}
            onCancel={() => {
              setSelectedSupplierRows([])
              setCurrentRow(undefined)
              setStockModalVisible(false)
            }}
          >
            {
              !!access.getSupplierByPro ?
                <ProTable<supplierByProItem>
                  headerTitle={`【${currentRow?.oil_name}】仓库列表`}
                  loading={false}
                  actionRef={supplierListRef}
                  rowKey="oil_depot_id"
                  bordered={true}
                  search={{
                    resetText: '重置查询',
                    searchText: '查询仓库',
                  }}
                  pagination={{
                    pageSize: 10,
                    current: 1,
                  }}
                  request={async (params) => {
                    const dataParams = {
                      page: params.current,
                      limit: params.pageSize,
                      product_id: currentRow?.id,
                    }
                    const res = await getSupplierByPro({ ...dataParams });
                    return {
                      data: res.data.list,
                      success: res.code === 200,
                      total: res.data.list.length,
                    };
                  }}
                  rowSelection={{
                    onChange: (_, selectedRows) => {
                      setSelectedSupplierRows(selectedRows);
                    },
                  }}
                  columns={[
                    {
                      title: '仓库名称',
                      dataIndex: 'supplier_name',
                      render: (dom, rowData) => {
                        if (rowData.is_xn === 2) {
                          return (
                            <Space><span>{dom}</span> <Tag color={'#108ee9'}>虚拟仓库</Tag></Space>
                          );
                        } else {
                          return (
                            `${dom}`
                          );
                        }
                      }
                    },
                    {
                      title: '库存余量',
                      align: 'right',
                      dataIndex: 'stocks',
                      hideInSearch: true,
                      render: (value, rowData) => {
                        return (
                          !!value && `${value} ${currentRow?.unit}`
                        )
                      },
                    },
                    {
                      title: '操作',
                      width: 300,
                      valueType: 'option',
                      render: (dom, rowData) => [
                        rowData.is_xn === 1 && !!access.reduceOilStock &&
                        <Button
                          key="reduceOutOilStock"
                          disabled={rowData.stocks === 0}
                          danger
                          shape="round"
                          icon={<ExportOutlined />}
                          onClick={() => {
                            setCurrentId(rowData.oil_depot_id);
                            setExportModalVisible(true)
                          }}
                        >出库</Button>,
                        !!access.transOilStock &&
                        <Button
                          key="transOilStock"
                          type="primary"
                          disabled={rowData.stocks === 0}
                          shape="round"
                          icon={<PartitionOutlined />}
                          onClick={() => {
                            setCurrentId(rowData.oil_depot_id);
                            setTransModalVisible(true)
                          }}
                        >库存转移</Button>,
                        !!access.getInStockList &&
                        <Button
                          key="getInStockList"
                          type="primary"
                          ghost
                          disabled={rowData.stocks === 0}
                          icon={<UnorderedListOutlined />}
                          onClick={() => {
                            setCurrentId(rowData.oil_depot_id);
                            setOrderModalVisible(true)
                          }}
                        >入库批次</Button>,
                        rowData.is_xn === 1 && !!access.lossOilStock &&
                        <Button
                          key="lossStock"
                          type="primary"
                          disabled={rowData.stocks === 0}
                          danger
                          shape="round"
                          icon={<DeleteOutlined />}
                          onClick={() => {
                            setCurrentId(rowData.oil_depot_id);
                            setLossStockModalVisible(true)
                          }}
                        >库存报损</Button>,
                      ],
                    }
                  ]
                  }
                />
                : '您没有权限查看'
            }
            {selectedSupplierRowsState.length > 0 && (
              <FooterToolbar
                extra={
                  <div>
                    已选择{' '}
                    <a
                      style={{
                        fontWeight: 600,
                      }}
                    >
                      {selectedSupplierRowsState?.length}
                    </a>
                    项 &nbsp;&nbsp;
                    <span>
                      总库存余量： {selectedSupplierRowsState?.reduce((pre, item) => pre + Number(item.stocks)!, 0)} {currentRow?.unit}
                    </span>&nbsp;&nbsp;&nbsp;&nbsp;
                  </div>
                }
              >
              </FooterToolbar>
            )}
          </Modal>
        )
      }





      {/* 入库批次 */}
      {
        !!orderModalVisible && (
          <Modal
            title="入库批次列表"
            width={1200}
            visible={orderModalVisible}
            onCancel={() => {
              setCurrentId(undefined)
              setOrderModalVisible(false)
            }}
            footer={null}
          >
            <ProTable
              rowKey="id"
              search={false}
              request={async (params) => {
                const dataParams = {
                  oildepot_id: currentId,
                  product_id: currentRow?.id,
                  page: params.current,
                  limit: params.pageSize,
                }
                const res = await getInStockList({ ...dataParams });
                return {
                  data: res.data.list,
                  success: res.code === 200,
                  total: res.data.total,
                };
              }}
              columns={[
                {
                  title: '入库批次号',
                  width: 300,
                  dataIndex: 'pc_no',
                  copyable: true,
                },
                {
                  title: '入库量',
                  dataIndex: 'add_stock',
                },
                {
                  title: '入库时间',
                  dataIndex: 'stock_date',
                },
                {
                  title: '入库供应商',
                  dataIndex: 'provider_name',
                },
              ]
              }
              pagination={{
                pageSize: 10,
                current: 1,
              }}>
            </ProTable>
          </Modal>
        )
      }


      {/* 货品详情 */}
      {currentRow?.id && !!showDetail && (
        <Drawer
          width={700}
          visible={showDetail}
          onClose={() => {
            setCurrentRow(undefined);
            setShowDetail(false);
          }}
          closable={true}
        >
          <ProDescriptions<oilInfoParams>
            column={2}
            bordered={true}
            title='货品详情'
            request={async () => {
              const params = {
                oil_id: currentRow.id,
              }
              const res = await getOilInfo({ ...params });
              const data = res.data.info

              return {
                data: data
              };
            }}
            columns={[
              // {
              //   title: '货品ID',
              //   dataIndex: 'id',
              // },
              {
                title: '状态',
                dataIndex: 'is_checked',
                valueEnum: {
                  0: { text: '未启用', status: 'Default', },
                  1: { text: '启用中', status: 'Success', },
                },
              },
              {
                title: '货品名称',
                dataIndex: 'oil_name',
              },

              {
                title: '货品类型',
                dataIndex: 'oil_type',
              },
              {
                title: '参考单价',
                dataIndex: 'price',
                renderText: (value, rowData) => {
                  value ? `¥ ${value} / ${rowData.unit}` : ''
                }

              },
              {
                title: '库存余量',
                dataIndex: 'stock',
                renderText: (value, rowData) => !!value ? `${value} ${rowData.unit}` : '',
              },
              {
                title: '条形码',
                dataIndex: 'bar_code',
              },
              {
                title: '品牌',
                dataIndex: 'brand',
              },
              {
                title: '规格',
                dataIndex: 'specs',
              },
              {
                title: '产地',
                dataIndex: 'producing_area',
              },
              {
                title: '备注',
                dataIndex: 'remarks',
              },
            ]}
          />
        </Drawer>
      )}


    </PageContainer>
  );
};

export default TableList;